import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 构造transwarp更新语句的工具类
 * @Date: 2020/2/13
 * @Time: 13:20
 * @Created by:   dingtao
 * @Modified by:
 * @Modified at:
 */
@Slf4j
public class TranswarpSqlUtil {

    /**
     * 索引名称
     */
    private String indexName;

    /**
     * 值集
     */
    private Map<String, Object> values;

    /**
     * 主键名称
     */
    private String idKey;

    /**
     * sql语句
     */
    private StringBuilder sql;


    public static TranswarpSqlUtil builder(){
        return new TranswarpSqlUtil();
    }

    public TranswarpSqlUtil setIndexName(String indexName){
        this.indexName = indexName;
        return this;
    }

    public TranswarpSqlUtil setValues(Map<String, Object> values){
        this.values = values;
        return this;
    }

    public TranswarpSqlUtil setIdKey(String idKey){
        this.idKey = idKey;
        return this;
    }


    /**
     * 准备更新语句
     * @return
     */
    public TranswarpSqlUtil prepareUpdate(){
        sql = new StringBuilder();
        String id = String.valueOf(values.get(idKey));
        sql.append("udpate ").append(indexName).append(" set ");

        List<String> updateValueList =
        values.entrySet().stream()
                //清除id列
                .filter(entry->!entry.getKey().equalsIgnoreCase(id))
                //转化为key='value'格式
                .map(entry->entry.getKey().concat("='").concat(String.valueOf(entry.getValue())).concat("'"))
                .collect(Collectors.toList());
        sql.append(StringUtils.join(updateValueList, ", "));

        sql.append(" where ").append(idKey).append(" = '").append(id).append("'");
        return this;
    }

    public String toSql2(){
//        System.out.println(JSONObject.toJSONString(this.sql));
        String resultSql = sql.toString();
        sql = null; //help for GC
//        System.out.println(resultSql);
        return resultSql;
    }


}
